import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:非递归遍历二叉树
 * User: LXW
 * Date: 2022-02-28
 * Time: 21:32
 */
class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}
public class Test {

    /**
     *
     * @param root
     */
    void preOrderNor(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }

            TreeNode top = stack.pop();
            cur = top.right;
        }
    }

    void inOrderNor(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(top.val+" ");
            cur = top.right;
        }
    }

    void postOrderNor(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }

            TreeNode top = stack.peek();
            //如果当前节点的右子树被打印过 或者 遍历过  直接弹出了
            if (top.right == null || top.right == prev) {
                stack.pop();
                System.out.print(top.val+" ");
                prev = top;//记录一下 最近一次打印的节点
            } else {
                cur = top.right;
            }
        }
    }
}
